<template>
  <view class="container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="header-content">
        <uni-icons @click="onBack" type="left" size="20" class="icon"></uni-icons>
        <text class="title">铅封库存</text>
        <view class="header-icons">
          <uni-icons @click="toggleSearch" type="search" size="20" class="icon"></uni-icons>
          <uni-icons @click="toggleFilter" type="paperplane" size="20" class="icon"></uni-icons>
          <uni-icons @click="resetFilters" type="refresh" size="20" class="icon"></uni-icons>
        </view>
        <!-- 搜索输入框 -->
        <view v-if="showSearch" class="search-input">
          <input v-model="searchCode" placeholder="请输入铅封编号" @input="onSearch"/>
        </view>
        <!-- 筛选下拉框 -->
        <view v-if="showFilter" class="filter-select">
          <picker
              v-model="searchStatus"
              :range="Object.values(statusOptions).map(item => item.text)"
              @change="onPickerChange"
          >
            <view class="status-tag" :style="statusOptions[searchStatus]?.style">
              {{ getStatusLabel(searchStatus) || '请选择铅封状态' }}
            </view>
          </picker>
        </view>
      </view>
      <!-- Tab 栏 -->
      <view class="tabs">
        <view
            v-for="(tab, index) in tabs"
            :key="`tab-${index}-${tab.count}`"
            class="tab-item"
            :class="{ active: activeTab === tab.name }"
            @click="onTabClick(tab.name)"
        >
          <div class="tab-text">
            <span class="tab-label">{{ tab.label }}</span>
            <span class="tab-count">({{ tab.count }})</span>
          </div>
        </view>
      </view>
    </view>

    <!-- 列表内容 -->
    <scroll-view
        class="list-container"
        scroll-y
        @scrolltolower="onScrollToLower"
        @scrolltoupper="onScrollToUpper"
    >
      <view v-if="currentList.length === 0" class="empty">
        <text>暂无数据</text>
      </view>
      <view v-else class="list">
        <view
            v-for="item in currentList"
            :key="item.id"
            class="list-item"
            @click="showDetail(item.id)"
        >
          <view class="item-content">
            <view class="item-main">
              <text class="item-code">{{ item.code }}</text>
              <text class="item-time">入库批次：{{ item.inTime }}</text>
              <text class="item-target">使用对象：{{ item.target }}</text>
            </view>
            <view class="status-tag" :style="statusOptions[item.status]?.style">
              {{ getStatusLabel(item.status) }}
            </view>
          </view>
        </view>
      </view>
      <!-- 加载中提示 -->
      <view v-if="isLoading" class="loading-center">
        <text>加载中...</text>
      </view>
      <!-- 已经到底提示 -->
      <view v-if="isEnd" class="end-center">
        <text>已经到底了</text>
      </view>
    </scroll-view>

    <!-- 详情弹窗 -->
    <view class="popup-mask" v-if="showDetailPopup">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-code">{{ detailData?.code }}</text>
          <text @click="closeDetail" class="popup-close-x">×</text>
        </view>
        <view v-if="detailLoading">
          <text>加载中...</text>
        </view>
        <view v-else-if="detailData">
          <view class="popup-row">
            <text class="popup-label">入库批次</text>
            <text class="popup-value">{{ detailData.inDate }}</text>
          </view>
          <view class="popup-row">
            <text class="popup-label">使用对象</text>
            <text class="popup-value">{{ detailData.target }}</text>
          </view>
          <view class="popup-row">
            <text class="popup-label">厂家</text>
            <text class="popup-value">{{ detailData.brand }}</text>
          </view>
          <view class="popup-row">
            <text class="popup-label">是否外部铅封</text>
            <text class="popup-value">{{ detailData.isOut }}</text>
          </view>
          <view class="popup-row">
            <text class="popup-label">状态</text>
            <view
                class="status-tag"
                :style="statusOptions[detailData.status]?.style"
            >
              {{ getStatusLabel(detailData.status) }}
            </view>
          </view>
        </view>
        <button class="vue-button" @click="onReceive">溯源记录</button>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {computed, nextTick, onMounted, ref} from 'vue';
import {debounce} from 'lodash-es';
import {findAllTblSealno, findSealnoDetailById, findSealnoType} from "@/api/function/sealnoStock/sealnoStock";

// 定义接口
interface TabItem {
  name: string;
  label: string;
  count: number;
}

interface ListItem {
  id: number;
  code: string;
  inTime: string;
  status: string;
  target: string;
}

// 定义响应式数据
const activeTab = ref<string | null>(null);
const tabs = ref<TabItem[]>([]);
const listData = ref<Record<string, ListItem[]>>({});
const currentPage = ref<Record<string, number>>({});
const pageSize = 10;
const isLoading = ref(false);
const isEnd = ref(false);
const showSearch = ref(false);
const showFilter = ref(false);
const searchCode = ref('');
const searchStatus = ref('');
const statusOptions = {
  ACTIVED: { text: '已入库', style: { color: '#52c41a' } },    // 绿色 - 表示正常可用状态
  LOCKED: { text: '锁定', style: { color: '#faad14' } },       // 黄色 - 表示临时不可用
  USING: { text: '已使用', style: { color: '#1890ff' } },      // 蓝色 - 表示正在使用中
  UERSED: { text: '已作废', style: { color: '#bfbfbf' } },     // 浅灰色 - 表示已作废
  DESTROYED: { text: '已销毁', style: { color: '#595959' } },   // 深灰色 - 表示已销毁
  ERROR: { text: '异常', style: { color: '#ff4d4f' } }         // 红色 - 表示错误状态
};
const showDetailPopup = ref(false);
const detailData = ref<ListItem | null>(null);
const detailLoading = ref(false);
const currentSnCode = ref('');
const selectedSeal = ref('');
const selectedStatus = ref('');
const sealList = ref([]);

// 获取状态标签
const getStatusLabel = (value: string) => {
  const option = statusOptions[value];
  return option ? option.text : '';
};

// 获取状态对应的类名
const getStatusClass = (value: string) => {
  const option = statusOptions[value];
  return option ? value.toLowerCase() : '';
};

// 切换搜索显示状态
const toggleSearch = async () => {
  showSearch.value = !showSearch.value;
  if (showSearch.value) {
    showFilter.value = false;
  }
  await fetchTabsData();
  if (activeTab.value) {
    listData.value[activeTab.value] = [];
    currentPage.value[activeTab.value] = 1;
    isEnd.value = false;
    await fetchListData(activeTab.value, 1);
  }
};

// 重置筛选条件
const resetFilters = async () => {
  searchCode.value = '';
  searchStatus.value = '';
  await fetchTabsData();
  if (activeTab.value) {
    listData.value[activeTab.value] = [];
    currentPage.value[activeTab.value] = 1;
    isEnd.value = false;
    await fetchListData(activeTab.value, 1);
  }
};

// 切换筛选显示状态
const toggleFilter = async () => {
  showFilter.value = !showFilter.value;
  if (showFilter.value) {
    showSearch.value = false;
  }
  await fetchTabsData();
  if (activeTab.value) {
    listData.value[activeTab.value] = [];
    currentPage.value[activeTab.value] = 1;
    isEnd.value = false;
    await fetchListData(activeTab.value, 1);
  }
};

// 选择筛选条件
const onPickerChange = (e) => {
  const selectedText = Object.values(statusOptions)[e.detail.value].text;
  const selectedKey = Object.keys(statusOptions).find(key => statusOptions[key].text === selectedText);
  searchStatus.value = selectedKey || '';
  onFilter();
};

// 获取 Tab 数据
const fetchTabsData = async () => {
  try {
    const res = await findSealnoType(searchCode.value, searchStatus.value);
    if (res.code === 200) {
      tabs.value = res.data.map((item: any) => ({
        name: item.code,
        label: item.name,
        count: item.count || 0
      }));
      if (tabs.value.length > 0) {
        activeTab.value = tabs.value[0].name;
        currentPage.value[activeTab.value] = 1;
        await fetchListData(activeTab.value, 1);
      }
      await nextTick();
      const tabItems = document.querySelectorAll('.tab-item');
      tabItems.forEach(item => {
        item.offsetHeight; // 触发重排
      });
    }
  } catch (error) {
    console.error('Failed to fetch tabs:', error);
  }
};

// 新增退出按钮点击事件处理函数
const onBack = () => {
  uni.switchTab({
    url: '/pages/index'
  });
};

// 获取列表数据
const fetchListData = async (tabName: string, page: number) => {
  if (isLoading.value) return;
  isLoading.value = true;
  try {
    const res = await findAllTblSealno(
        tabName,
        page,
        pageSize,
        searchCode.value,
        searchStatus.value
    );
    if (res.code === 200) {
      const mappedData = res.rows.map((sealno: any) => ({
        id: sealno.id,
        code: sealno.snCode,
        inTime: sealno.inDate,
        status: sealno.status,
        target: sealno.deviceName
      }));
      if (!listData.value[tabName]) {
        listData.value[tabName] = [];
      }
      listData.value[tabName] = listData.value[tabName].concat(mappedData);
      isEnd.value = listData.value[tabName].length > 0 && mappedData.length < pageSize;
      if (mappedData.length >= pageSize) {
        currentPage.value[tabName] = page + 1;
      }
    }
  } catch (error) {
    console.error(`Failed to fetch list data for ${tabName}:`, error);
  } finally {
    isLoading.value = false;
  }
};

// 显示详情弹窗
const showDetail = async (id: number) => {
  detailLoading.value = true;
  try {
    const res = await findSealnoDetailById(id);
    if (res.code === 200) {
      detailData.value = {
        id: res.data.id,
        code: res.data.snCode,
        inDate: res.data.inDate,
        status: res.data.status,
        target: res.data.deviceName,
        checkCode: res.data.checkCode,
        brand: res.data.brand,
        isOut: res.data.isOut
      };
      currentSnCode.value = res.data.snCode;
    }
  } catch (error) {
    console.error('Failed to fetch detail data:', error);
  } finally {
    detailLoading.value = false;
    showDetailPopup.value = true;
  }
};

// 点击 Tab 项
const onTabClick = async (tabName: string) => {
  if (activeTab.value !== tabName) {
    activeTab.value = tabName;
    listData.value[tabName] = [];
    currentPage.value[tabName] = 1;
    isEnd.value = false;
    await fetchListData(tabName, 1);
  }
};

// 滚动到底部加载更多
const onScrollToLower = () => {
  if (activeTab.value && !isEnd.value) {
    const page = currentPage.value[activeTab.value];
    fetchListData(activeTab.value, page);
  }
};

// 滚动到顶部加载上一页
const onScrollToUpper = () => {
  if (activeTab.value && currentPage.value[activeTab.value] > 1) {
    const prevPage = currentPage.value[activeTab.value] - 1;
    fetchListData(activeTab.value, prevPage);
  }
};

// 使用防抖处理搜索方法
const onSearch = debounce(async () => {
  await fetchTabsData();
  if (activeTab.value) {
    listData.value[activeTab.value] = [];
    currentPage.value[activeTab.value] = 1;
    isEnd.value = false;
    await fetchListData(activeTab.value, 1);
  }
}, 300);

// 筛选操作
const onFilter = debounce(async () => {
  await fetchTabsData();
  if (activeTab.value) {
    listData.value[activeTab.value] = [];
    currentPage.value[activeTab.value] = 1;
    isEnd.value = false;
    await fetchListData(activeTab.value, 1);
  }
}, 300);

// 计算当前列表数据
const currentList = computed(() => {
  return activeTab.value ? listData.value[activeTab.value] || [] : [];
});

// 关闭详情弹窗
const closeDetail = () => {
  showDetailPopup.value = false;
};

// 点击溯源记录按钮
const onReceive = () => {
  if (currentSnCode.value) {
    uni.navigateTo({
      url: `/pages/function/sealnoOperate/index?snCode=${currentSnCode.value}`
    });
  }
};

// 初始化
onMounted(() => {
  fetchTabsData();
});
</script>

<style>
/* 页面整体样式 */
page {
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f5f5f5;
}

/* 顶部导航样式 */
.header {
  background-color: #ffffff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  flex-shrink: 0;
  position: fixed;
  top: 10px;
  left: 0;
  right: 0;
  z-index: 1000;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
}

.title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
}

.header-icons {
  display: flex;
  align-items: center;
  gap: 30rpx;
}

.icon {
  color: #666666;
}

/* Tab 栏样式 */
.tabs {
  display: flex;
  padding: 0 20rpx;
  border-bottom: 1px solid #f0f0f0;
}

.tab-item {
  flex: 1;
  padding: 20rpx 0;
  text-align: center;
}

.tab-text {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-size: 28rpx;
  color: #666666;
}

.tab-label {
  font-size: 28rpx;
  color: #666666;
}

.tab-count {
  font-size: 28rpx;
  color: #666666;
}

.active .tab-text,
.active .tab-label,
.active .tab-count {
  color: #2979ff;
  font-weight: 500;
}

/* 列表内容样式 */
.list-container {
  flex: 1;
  overflow: auto;
  margin-top: 120rpx;
}

.list {
  padding: 20rpx;
}

.list-item {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.item-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.item-main {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.item-code {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
}

.item-time,
.item-target {
  font-size: 24rpx;
  color: #999999;
}

.status-tag {
  background: none !important;
  border: none !important;
  padding: 0 !important;
}

.empty {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400rpx;
  color: #999999;
  font-size: 28rpx;
}

/* 加载提示样式 */
.loading-center {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
  padding: 10px 0;
}

.end-center {
  display: flex;
  justify-content: center;
  align-items: center;
  color: #999;
  padding: 10px 0;
}

/* 搜索与筛选样式 */
.search-input {
  display: flex;
  align-items: center;
}

.filter-select {
  display: flex;
  align-items: center;
}

.filter-select .status-tag {
  padding: 4px 16px;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
  min-width: 80px;
  transition: background-color 0.3s ease;
}

/* 详情弹窗样式 */
.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1001;
}

.popup-content {
  background-color: #fff;
  padding: 20px;
  border-radius: 15px;
  width: 80%;
  max-width: 350px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.popup-code {
  font-size: 18px;
  font-weight: bold;
}

.popup-close-x {
  font-size: 24px;
  cursor: pointer;
  color: #333;
}

.popup-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.popup-label {
  text-align: left;
}

.popup-value {
  text-align: right;
}

.vue-button {
  width: 100%;
  margin-top: 20px;
  background-color: #2979ff;
  color: white;
  border: none;
  padding: 6px 10px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  line-height: 1.5;
}
</style>
